﻿using DotNetty.Buffers;
using DotNetty.Codecs;
using DotNetty.Transport.Channels;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TestNetty.Service.Model;

namespace TestNetty.Client.Handlers
{
    /// <summary>
    /// 编码器（将消息对象转换为JSON格式的ByteBuf）
    /// </summary>
    public class JsonEncoder : MessageToByteEncoder<MyMessage>
    {
        protected override void Encode(IChannelHandlerContext context, MyMessage message, IByteBuffer output)
        {
            try
            {
                string json = JsonConvert.SerializeObject(message);//序列化接受的json字符串
                byte[] bytes = Encoding.UTF8.GetBytes(json);// 将字符串转换为字节
                output.WriteBytes(bytes);//将序列化后的字节输出
            }
            catch (Exception)
            {
                throw;
            }

        }
    }
}
